﻿#include "elk_web_view.h"
#include "ui_elk_web_view.h"
#include "elk_common_dlg.h"
#include <QFileDialog>
#include <QStandardPaths>

ElkWebView::ElkWebView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ElkWebView)
{
    ui->setupUi(this);
    ui->lineEditURL->setText(QString("www.bing.com"));

    delegate_.reset(new ElkWebDelegate(ui->widgetPage), [](ElkWebDelegate *) {});
    connect(delegate_.get(), SIGNAL(gotFocus()),
            this, SLOT(onGotFocus()));
    connect(delegate_.get(), SIGNAL(takeFocus()),
            this, SLOT(onTakeFocus()));
    connect(delegate_.get(), SIGNAL(urlChanged(const QString &)),
            this, SLOT(onUrlChanged(const QString &)));
    connect(delegate_.get(), SIGNAL(loadingProgressChanged(double)),
            this, SLOT(onLoadingProgressChanged(double)));
}

ElkWebView::~ElkWebView()
{
    delete ui;
}

QWeakPointer<ElkWebDelegate> ElkWebView::delegate()
{
    return delegate_;
}

void ElkWebView::onGotFocus()
{
    this->setFocus();
}

void ElkWebView::onTakeFocus()
{
    this->clearFocus();
}

void ElkWebView::onUrlChanged(const QString &url)
{
    ui->lineEditURL->setText(url);
}

void ElkWebView::onLoadingProgressChanged(double progress)
{
    if (qFuzzyIsNull(progress) || qFuzzyCompare(progress, 1.0)) {
        ui->progressBar->setValue(0);
    } else {
        ui->progressBar->setValue(progress * 100);
    }
}

void ElkWebView::on_lineEditURL_returnPressed()
{
    QString url = ui->lineEditURL->text();
    if (url.isEmpty()) {
        return;
    }
    delegate_->load(QUrl::fromUserInput(url).toString().toStdString().c_str());
}

void ElkWebView::on_pushButtonLoad_clicked()
{
    QString url = ui->lineEditURL->text();
    if (url.isEmpty()) {
        QString folder = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
        auto fileName = QFileDialog::getOpenFileName(this->window(), QString(),
                                                     folder, QString("*.html"));
        if (!fileName.isEmpty()) {
            delegate_->load(QUrl::fromLocalFile(fileName).toString().toStdString().c_str());
        }
    } else {
        delegate_->load(QUrl::fromUserInput(url).toString().toStdString().c_str());
    }
}

void ElkWebView::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    delegate_->createAsChild(ui->widgetPage);
}

void ElkWebView::focusInEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
    delegate_->setFocus();
}

void ElkWebView::focusOutEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
    delegate_->clearFocus();
}

void ElkWebView::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    delegate_->resize(ui->widgetPage->size());
}
